<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Reimburse;

use App\Util\SerialNo;
use App\Models\Basics\ExchangeRate;
use App\Models\Product\ProductAmazonSku;
use App\Models\Reimburse\ReimburseApply;
use App\Models\Reimburse\ReimbursePaid;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
class ApplyAjax {

    /**
     * 申请
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function apply($id){
        try{
            DB::beginTransaction();
            $rp = ReimbursePaid::query()->find($id);
            if($rp->apply_status != 1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '状态有误！']);
            }
            if($rp->order_by != 3){
                if(!$rp->paid_amount){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '金额不能为空或0！']);
                }
                if($rp->order_by == 4){
                    if(!$rp->paid_account_no){
                        DB::rollBack();
                        return response()->json(['status' => false, 'message' => '佣金账号不能为空！']);
                    }
                    if(!$rp->currency_code){
                        DB::rollBack();
                        return response()->json(['status' => false, 'message' => '佣金币种不能为空！']);
                    }
                }
            }else{
                $ra = ReimburseApply::query()->where('reimburse_no',$rp->reimburse_no)->first();
                if(!$ra->order_atten){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '多次返款订单联系人不能为空！']);
                }
            }
            $rp->apply_status = 2;
            if(is_null($rp->paid_amount)){
                $rp->paid_amount = 0;
            }
            $flag1 = $rp->save();
            if(!$flag1){
                DB::rollBack();
                return response()->json(['status' => true, 'message' => '操作失败！']);
            }
            $flag2 = ReimburseApply::query()
                ->where('reimburse_no',$rp->reimburse_no)
                ->update(['apply_status' => 2,'audit_status' => 1]);
            if($flag2){
                DB::commit();
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }else{
                DB::rollBack();
                return response()->json(['status' => true, 'message' => '操作失败！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误！']);
        }
    }

    /**
     * 撤回
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function revoke($id){
        try{
            DB::beginTransaction();
            $rp = ReimbursePaid::query()->find($id);
            if($rp->paid_status != 1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '状态有误！']);
            }
            $rp->apply_status = 1;
            $rp->audit_status = 1;
            $flag1 = $rp->save();
            if(!$flag1){
                DB::rollBack();
                return response()->json(['status' => true, 'message' => '操作失败！']);
            }
            $_rp = ReimbursePaid::query()
                ->where('reimburse_no',$rp->reimburse_no)
                ->where('apply_status',2)
                ->first();
            if($_rp){
                if($_rp->audit_status == 1){
                    $auditStatus = 1;
                }else{
                    $auditStatus = 2;
                }
                $flag2 = ReimburseApply::query()
                    ->where('reimburse_no',$rp->reimburse_no)
                    ->update(['apply_status' => 2,'audit_status' => $auditStatus]);
            }else{
                $flag2 = ReimburseApply::query()
                    ->where('reimburse_no',$rp->reimburse_no)
                    ->update(['apply_status' => 1,'audit_status' => 1]);
            }
            if($flag2){
                DB::commit();
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }else{
                DB::rollBack();
                return response()->json(['status' => true, 'message' => '操作失败！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误！']);
        }
    }

    public function add($param){
        $apply = $param['apply'];
        $paid = $param['paid'];
        if(($apply['fee_type'] == 1 || $apply['fee_type'] == 2)){
            if($apply['fee_type'] == 1){
                if(!$apply['r_type']){
                    return response()->json(['status' => false, 'message' => '刷单类型不能为空！']);
                }
            }
            if(!$apply['seller_sku']){
                return response()->json(['status' => false, 'message' => '亚马逊SKU不能为空！']);
            }
            $pas = ProductAmazonSku::query()
                ->where('country_id',$apply['country_id'])
                ->where('seller_sku',$apply['seller_sku'])
                ->first();
            if(!$pas){
                return response()->json(['status' => false, 'message' => '系统未匹配到该亚马逊SKU！']);
            }
        }elseif($apply['fee_type'] == 4){
            if(!$apply['asin']){
                return response()->json(['status' => false, 'message' => 'ASIN不能为空！']);
            }
            $pas = ProductAmazonSku::query()
                ->where('country_id',$apply['country_id'])
                ->where('asin',$apply['asin'])
                ->first();
            if(!$pas){
                return response()->json(['status' => false, 'message' => '系统未匹配到该ASIN！']);
            }
        }else{
            if($apply['seller_sku']){
                $pas = ProductAmazonSku::query()
                    ->where('country_id',$apply['country_id'])
                    ->where('seller_sku',$apply['seller_sku'])
                    ->first();
                if(!$pas){
                    return response()->json(['status' => false, 'message' => '系统未匹配到该亚马逊SKU！']);
                }
            }
        }
        try{
            $userId = Admin::user()->id;
            DB::beginTransaction();
            $apply['reimburse_no'] = SerialNo::getRaNo();
            $apply['seller_id'] = isset($pas) ? $pas->seller_id : $userId;
            $apply['psku_id'] = isset($pas) ? $pas->psku_id : null;
            $paidMethod = $apply['paid_method'];
            $apply['apply_status'] = $paidMethod != 5 ? 1 : 2;
            $apply['audit_status'] = $paidMethod != 5 ? 1 : 2;
            $apply['paid_status'] = $paidMethod != 5 ? 1 : 3;
            $apply['operator_id'] = $userId;
            $date = date('Y-m-d H:i:s');
            $rd = [];
            $rd['fee_type'] = $apply['fee_type'];
            $rd['r_type'] = $apply['r_type'];
            $rd['order_no'] = $apply['order_no'];
            $rd['country_id'] = $apply['country_id'];
            $rd['seller_sku'] = $apply['seller_sku'];
            $rd['seller_id'] = $apply['seller_id'];
            $rd['psku_id'] = $apply['psku_id'];
            $rd['paid_method'] = $paidMethod;
            $rd['paid_account_no'] = $apply['paid_account_no'];
            $rd['currency_code'] = $apply['currency_code'];
            $rd['remarks'] = $apply['remarks'];
            $rd['rate_odds'] = $paidMethod != 5 ? null : ExchangeRate::getRateOddsToRMB($apply['currency_code'],strtotime($date));
            $rd['paid_status'] = $paidMethod != 5 ? 1 : 3;
            $rd['paid_date'] = $paidMethod != 5 ? null : $date;
            $rd['report_date'] = $paidMethod != 5 ? null : date('Y-m-01',strtotime($date));
            if($apply['paid_type'] == 3 && $paidMethod == 5){
                $rd['paid_date_4'] = $date;
            }
            $paidItem = [];
            foreach ($paid as $k => $item){
                $rd['paid_amount_'.$k] = is_null($item['paid_amount']) ? 0 : $item['paid_amount'];
                $paidItem[$k]['order_by'] = $k;
                $paidItem[$k]['paid_amount'] = is_null($item['paid_amount']) ? 0 : $item['paid_amount'];
                $paidItem[$k]['apply_status'] = $paidMethod != 5 ? 1 : 2;
                $paidItem[$k]['audit_status'] = $paidMethod != 5 ? 1 : 2;
                $paidItem[$k]['paid_status'] = $paidMethod != 5 ? 1 : 2;
                $paidItem[$k]['paid_date'] = $paidMethod != 5 ? null : $date;
                if($k != 4){
                    $paidItem[$k]['paid_method'] = $paidMethod;
                    $paidItem[$k]['paid_account_no'] = $apply['paid_account_no'];
                    $paidItem[$k]['currency_code'] = $apply['currency_code'];
                }else{
                    $rd['rate_odds_4'] = $paidMethod != 5 ? null : ExchangeRate::getRateOddsToRMB($item['currency_code'],strtotime($date));
                    $rd['paid_method_4'] = $item['paid_method'];
                    $rd['paid_account_no_4'] = $item['paid_account_no'];
                    $rd['currency_code_4'] = $item['currency_code'];
                    $paidItem[$k]['paid_method'] = $item['paid_method'];
                    $paidItem[$k]['paid_account_no'] = $item['paid_account_no'];
                    $paidItem[$k]['currency_code'] = $item['currency_code'];
                }
            }
            $ra = ReimburseApply::create($apply);
            $ra->paid()->createMany($paidItem);
            $ra->detail()->create($rd);
            return response()->json(['status' =>true, 'message' => '操作成功！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误！']);
        }
    }
}
